package com.yao.securitydemo.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码
 */
@RestController
public class CaptchaController {

    @Autowired
    private Producer producer;

    /**
     * 生成图片验证码
     *
     * @param request  request
     * @param response response
     * @throws IOException IOException
     */
    @GetMapping("/captcha.jpg")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String code = producer.createText();
//        request.getSession().setAttribute("IMAGE_CODE", code);
//        BufferedImage image = producer.createImage(code);
//        ServletOutputStream outputStream = response.getOutputStream();
//        ImageIO.write(image, "jpg", outputStream);
        response.setContentType("image/jpeg");
        String text = producer.createText();
        request.getSession().setAttribute("captcha", text);
        //创建验证码图片
        BufferedImage image = producer.createImage(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image,"jpg",out);
        try {
            out.flush();
        }catch (Exception e){

        }finally {
            out.close();
        }
    }

}
